package cn.com.db.service;


import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.com.util.TimeUtil;
import cn.com.util.UidUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import cn.com.db.model.Cart;
import cn.com.db.model.CartItem;
import cn.com.db.model.Goods;
import cn.com.db.model.Store;

@Service
public class CartService extends BaseService {

    public void createCart(Cart cart){
        cartDao.createCart(cart);
    }

    public void createCart(String userAuthing){
        Cart cart=new Cart();
        cart.setId(UidUtil.createUUID());
        cart.setUser(userAuthing);
        cart.setCreated_at(TimeUtil.getNowTimestamp());
        createCart(cart);
    }
    public Cart getCartById(String cartId){
        return cartDao.getCartById(cartId);
    }

    public Cart getUserCart(String userId){
        return cartDao.getUserCart(userId);
    }

    public Cart viewCart(String userId){
        String cartId=cartDao.getUserCartId(userId);
        if(StringUtils.isBlank(cartId)){
            return null;
        }
        return cartDao.viewCart(cartId);
    }

    public void putItem(CartItem cartItem){
        cartItemDao.addCartItem(cartItem);
    }

    public BigDecimal countPrice(String cartId){
        List<CartItem> items=cartItemDao.getCartItems(cartId);
        return countPrice(items);
    }
    // mxq 改 加入了商店配送费用的计算  2018.4.10
    public BigDecimal countPrice(List<CartItem> items){
        BigDecimal sum=BigDecimal.valueOf(0);
        if (items==null||items.size()==0){
            return sum;
        }
        // 计算store的配送费,store配送费不能重复计算
        Set<String> stores = new HashSet<>();
        for (CartItem item:items){
            Goods goods=goodsDao.getGoodsById(item.getGoods());
            Store store = storeDao.getStoreById(goods.getStore());
            if(!stores.contains(store.getId())){
            	stores.add(store.getId());
            	sum=sum.add(store.getFreight());
            }
            sum=sum.add(goods.getPrice().multiply(BigDecimal.valueOf(item.getCount())));
        }
        return sum;
    }

    public BigDecimal countFreight(List<String> items){
        return cartItemDao.countCartItemFreight(items);
    }


}
